<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="110px">
                    <el-form-item label="优惠券名称" prop="name">
                      <el-input v-model="formData.name" placeholder="请输入优惠券名称" />
                    </el-form-item>
        <el-form-item label="优惠券类型" prop="useType">
          <el-radio-group v-model="formData.useType">
            <el-radio :label="1">通用券</el-radio>
            <el-radio :label="2">商品券</el-radio>
            <el-radio :label="3">品类券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.useType === 2" label="选择商品" prop="productId">
          <el-button @click="openProductDialog">选择商品</el-button>
          <div v-if="selectedProducts && selectedProducts.length" style="margin-top: 10px; display: flex; gap: 10px; flex-wrap: wrap;">
            <div v-for="(item, idx) in selectedProducts" :key="item.id" style="position: relative; width: 50px; height: 50px;">
              <img :src="item.image" alt="商品图片" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px; border: 1px solid #eee;" />
              <el-button
                type="danger"
                icon="el-icon-close"
                size="mini"
                circle
                style="position: absolute; top: -10px; right: -10px; padding: 0; width: 20px; height: 20px; min-width: 0;"
                @click.stop="removeProduct(idx)"
              ></el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="formData.useType === 3" label="商品分类" prop="cateId">
          <el-cascader
            v-model="selectedCategoryIds"
            :options="categoryOption"
            :props="{ checkStrictly: true }"
            clearable
            placeholder="请选择商品分类"
            @change="handleCategoryChange"
          />
        </el-form-item>
                    <el-form-item label="优惠券面值" prop="money">
          <el-input-number v-model="formData.money" :min="1" />
                    </el-form-item>
        <el-form-item label="使用门槛">
          <el-radio-group v-model="formData.thresholdType">
            <el-radio :label="0">无门槛</el-radio>
            <el-radio :label="1">有门槛</el-radio>
                      </el-radio-group>
                    </el-form-item>
        <el-form-item v-if="formData.thresholdType === 1" label="最低消费" prop="minPrice">
          <el-input-number v-model="formData.minPrice" :min="1" />
                    </el-form-item>
        <!-- <el-form-item label="优惠券最少领取" prop="limitPerUser">
          <el-input-number v-model="formData.limitPerUser" :min="1" />
        </el-form-item> -->
        <el-form-item label="使用有效期">
          <el-radio-group v-model="formData.validType">
            <el-radio :label="0">天数</el-radio>
            <el-radio :label="1">时间段</el-radio>
          </el-radio-group>
                    </el-form-item>
        <el-form-item v-if="formData.validType === 0" label="有效天数" prop="day">
          <el-input-number v-model="formData.day" :min="1" />
                    </el-form-item>
        <el-form-item v-if="formData.validType === 1" label="使用有效期" prop="validDateRange">
          <el-date-picker
            v-model="formData.validDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
                    </el-form-item>
        <el-form-item label="领取是否限时">
          <el-radio-group v-model="formData.receiveLimitType">
            <el-radio :label="0">限时</el-radio>
            <el-radio :label="1">不限时</el-radio>
                      </el-radio-group>
                    </el-form-item>
        <el-form-item v-if="formData.receiveLimitType === 0" label="领取时间" prop="receiveDateRange">
          <el-date-picker
            v-model="formData.receiveDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
                    </el-form-item>
        <el-form-item label="领取方式" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio :label="1">手动领取</el-radio>
            <el-radio :label="2">新人券</el-radio>
            <el-radio :label="3">赠送券</el-radio>
          </el-radio-group>
                    </el-form-item>
        <el-form-item label="是否限量" prop="isLimited">
          <el-radio-group v-model="formData.isLimited">
            <el-radio :label="1">限量</el-radio>
            <el-radio :label="0">不限量</el-radio>
          </el-radio-group>
                    </el-form-item>
        <el-form-item v-if="formData.isLimited === 1" label="发放数量" prop="total">
          <el-input-number v-model="formData.total" :min="1" />
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" />
                    </el-form-item>
        <el-form-item label="状态" prop="status">
                      <el-radio-group v-model="formData.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
                      </el-radio-group>
                    </el-form-item>
      </el-form>
              <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <ProductSelectDialog ref="productSelectDialog" @confirm="handleProductSelect" />
  </div>
</template>

<script>
  import * as StoreCouponApi from '@/api/discount/storecoupon';
  import ProductSelectDialog from '@/views/marketing/storeseckill/ProductSelectDialog.vue';
  import * as CategoryApi from '@/api/store/category';
      export default {
    name: "StoreCouponForm",
    components: {
      ProductSelectDialog,
                    },
    data() {
      return {
        // 弹出层标题
        dialogTitle: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
        // 表单参数
        formData: {
          name: '',
          useType: 1, // 优惠券类型
          money: 1,
          thresholdType: 0, // 0无门槛 1有门槛
          minPrice: 0,//最低消费
          limitPerUser: 1,
          validType: 0, // 0天数 1时间段
          day: 1,
          validDateRange: [],
          receiveLimitType: 0, // 0限时 1不限时
          receiveDateRange: [],
          receiveWay: 1, // 1手动 2新人 3赠送
          isLimited: 1, // 1限量 0不限量
          primaryKey: '',
          total: 1,
          lastTotal: 1, // 新增lastTotal属性，初始等于total
          sort: 0,
          status: 1
        },
        // 表单校验
        formRules: {
          name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
          money: [{ required: true, message: '请输入优惠券面值', trigger: 'blur' }],
          // ...其他校验
        },
        selectedProducts: [], // 多选商品数组
        categoryOption: [], // 分类级联数据
        selectedCategoryIds: [], // 选中的分类id数组
                        };
    },
    created() {
      this.getCategoryList();
    },
    methods: {
      /** 打开弹窗 */
     async open(id) {
        this.dialogVisible = true;
        this.reset();
        // 修改时，设置数据
        if (id) {
          this.formLoading = true;
          try {
            const res = await StoreCouponApi.getStoreCoupon(id);
            this.formData = res.data;
            this.title = "修改优惠券";
          } finally {
            this.formLoading = false;
          }
        }
        this.title = "新增优惠券";
              },
      /** 提交按钮 */
      async submitForm() {
        // 校验主表
        await this.$refs["formRef"].validate();
                  this.formLoading = true;
        try {
          const data = { ...this.formData };

          // 处理领取时间范围 - 只在选择了限时领取时才处理
          if (data.receiveLimitType === 0 && data.receiveDateRange && data.receiveDateRange.length === 2) {
            // 转换为时间戳，避免字符串时间转换问题
            data.receiveStartTime = new Date(data.receiveDateRange[0] + ' 00:00:00').getTime();
            data.receiveEndTime = new Date(data.receiveDateRange[1] + ' 23:59:59').getTime();
          } else {
            // 不限时领取，设置为 null
            data.receiveStartTime = null;
            data.receiveEndTime = null;
          }

          // 处理使用时间范围 - 只在选择了时间段时才处理
          if (data.validType === 1 && data.validDateRange && data.validDateRange.length === 2) {
            // 转换为时间戳，避免字符串时间转换问题
            data.useStartTime = new Date(data.validDateRange[0] + ' 00:00:00').getTime();
            data.useEndTime = new Date(data.validDateRange[1] + ' 23:59:59').getTime();
          } else {
            // 按天数计算，设置为 null
            data.useStartTime = null;
            data.useEndTime = null;
          }

          // 处理商品券
          if (data.useType === 2) {
            // 兜底：如果productIds没同步，尝试从selectedProducts同步
            if ((!data.productIds || !data.productIds.length) && this.selectedProducts && this.selectedProducts.length) {
              data.productIds = this.selectedProducts.map(item => item.id);
            }
            data.primaryKey = (data.productIds && data.productIds.length) ? data.productIds.join(',') : '';
            data.productId = data.primaryKey; // 如有用可保留
          }

          // 处理品类券
          if (data.useType === 3 && this.selectedCategoryIds && this.selectedCategoryIds.length > 0) {
            data.cateId = this.selectedCategoryIds[this.selectedCategoryIds.length - 1];
          }

                  // 修改的提交
          if (data.id) {
            await StoreCouponApi.updateStoreCoupon(data);
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.$emit('success');
            return;
          }
          // 添加的提交
          data.lastTotal = data.total;
          await StoreCouponApi.createStoreCoupon(data);
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.$emit('success');
        } finally {
          this.formLoading = false;
        }
      },
                      /** 表单重置 */
      reset() {
        this.formData = {
          name: '',
          useType: 1, // 优惠券类型
          money: 1,
          thresholdType: 0, // 0无门槛 1有门槛
          minPrice: 0,
          limitPerUser: 1,
          validType: 0, // 0天数 1时间段
          day: 1,
          validDateRange: [],
          receiveLimitType: 0, // 0限时 1不限时
          receiveDateRange: [],
          receiveWay: 1, // 1手动 2新人 3赠送
          isLimited: 1, // 1限量 0不限量
          primaryKey: '',
          total: 1,
          lastTotal: 1, // 重置时lastTotal等于total
          sort: 0,
          status: 1
        };
        this.resetForm("formRef");
        this.selectedProducts = []; // 重置时清空商品
      },
      openProductDialog() {
        this.$refs.productSelectDialog.open();
      },
      handleProductSelect(products) {
        this.selectedProducts = products;
        this.formData.productIds = products.map(item => item.id);
        this.formData.primaryKey = this.formData.productIds.join(','); // 用驼峰
      },
      removeProduct(idx) {
        this.selectedProducts.splice(idx, 1);
        this.formData.productIds = this.selectedProducts.map(item => item.id);
        this.formData.primaryKey = this.formData.productIds.join(',');
      },
      async getCategoryList() {
        const res = await CategoryApi.getCategoryList({ status: 1 });
        if (res.code === 0) {
          this.categoryOption = this.buildCascaderOptions(res.data);
        }
      },
      buildCascaderOptions(list) {
        const rootCategories = list.filter((category) => category.pid === 0);
        const buildChildren = (parentId, level = 1) => {
          const children = list
            .filter((category) => category.pid === parentId)
            .map((category) => {
              const option = {
                value: category.id,
                label: category.name,
              };
              if (level < 3) {
                const childOptions = buildChildren(category.id, level + 1);
                if (childOptions && childOptions.length > 0) {
                  option.children = childOptions;
                }
              }
              return option;
            });
          return children;
        };
        return rootCategories.map((category) => {
          const option = {
            value: category.id,
            label: category.name,
          };
          const children = buildChildren(category.id, 1);
          if (children && children.length > 0) {
            option.children = children;
          }
          return option;
        });
      },
      handleCategoryChange(ids) {
        // 只取最后一级分类id
        this.formData.cateId = ids.length ? ids[ids.length - 1] : null;
      },
    }
  };
</script>
